package com.jsm.twentyfour.service;

import com.jsm.twentyfour.constant.RoomAccountStatus;
import com.jsm.twentyfour.constant.RoomStatus;
import com.jsm.twentyfour.domain.Room;
import com.jsm.twentyfour.domain.RoomAccount;
import com.jsm.twentyfour.domain.RoomExample;
import com.jsm.twentyfour.dto.RoomAccountDTO;
import com.jsm.twentyfour.dto.RoomDTO;
import com.jsm.twentyfour.exception.BusinessException;
import com.jsm.twentyfour.mapper.BaseMapper;
import com.jsm.twentyfour.mapper.RoomMapper;
import com.jsm.twentyfour.request.ListRoomRequest;
import com.jsm.twentyfour.transfer.RoomAccountTransfer;
import com.jsm.twentyfour.transfer.RoomTransfer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * create by jsm on 2019/1/23
 */
@Service
public class RoomService extends BaseService <Room, RoomDTO, RoomExample> {
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private RoomAccountService roomAccountService;

    @Override
    public BaseMapper <Room, RoomExample> mapper() {
        return roomMapper;
    }

    @Override
    public Class <RoomDTO> getDTOClass() {
        return RoomDTO.class;
    }

    @Override
    public RoomDTO transfer(Room room) {
        return RoomTransfer.transfer(room);
    }

    public RoomDTO createRoom(Long userId) {
        RoomDTO roomDTO = insertSelective(Room.builder().createrId(userId).status(RoomStatus.OPEN).build());
        roomAccountService.insertSelective(RoomAccount.builder().roomId(roomDTO.getId()).userId(userId).status(RoomAccountStatus.IN).build());
        return roomDTO;
    }

    public RoomDTO joinRoom(Long userId, Long roomId) {
        RoomDTO room = getById(roomId);
        if (RoomStatus.CLOSE.equals(room.getStatus())) {
            throw new BusinessException("该房间已关闭,无法加入");
        }
        RoomAccountDTO roomAccount = roomAccountService.getByUserIdRoomIdStatus(userId, roomId, RoomAccountStatus.IN);
        if (roomAccount != null) {
            roomAccount.setStatus(RoomAccountStatus.LEAVE);
            roomAccountService.updateSelective(RoomAccountTransfer.transfer(roomAccount));
        }
        roomAccountService.insertSelective(RoomAccount.builder().status(RoomAccountStatus.IN).userId(userId).roomId(roomId).build());
        return room;
    }

    public void leaveRoom(Long userId, Long roomId) {
        RoomAccountDTO roomAccount = roomAccountService.getByUserIdRoomIdStatus(userId, roomId, RoomAccountStatus.IN);
        if (roomAccount != null) {
            roomAccount.setStatus(RoomAccountStatus.LEAVE);
            roomAccountService.updateSelective(RoomAccountTransfer.transfer(roomAccount));
        }
    }

    public PageList <RoomDTO> list(ListRoomRequest request) {

        RoomExample example = new RoomExample();
        example.createCriteria().andStatusEqualTo(RoomStatus.OPEN);
        return pagelistByExample(example, request.getPageNo(), request.getPageSize());

    }
}
